package com.software.loginregister.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.software.loginregister.R;
import com.software.loginregister.entity.ConversationHistory;

import java.util.ArrayList;
import java.util.List;

import lombok.NonNull;

public class ConversationHistoryAdapter extends RecyclerView.Adapter<ConversationHistoryAdapter.ViewHolder> {
    private Context context;
    private List<ConversationHistory> histories = new ArrayList<>();
    private OnItemClickListener listener;
    private OnItemLongClickListener onItemLongClickListener;

    public ConversationHistoryAdapter(Context context) {
        this.context = context;
        this.histories = new ArrayList<>();
    }


    public interface OnItemClickListener {
        void onItemClick(ConversationHistory history);
    }
    public interface OnItemLongClickListener {
        void onItemLongClick(ConversationHistory history);
    }


    public void setOnItemClickListener(OnItemClickListener listener) {
        this.listener = listener;
    }
    public void setOnItemLongClickListener(OnItemLongClickListener listener){
        this.onItemLongClickListener=listener;
    }

    public void setHistories(List<ConversationHistory> histories) {
        this.histories = histories;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_conversation_history, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        ConversationHistory history = histories.get(position);
        holder.tvTitle.setText(history.getName());
        holder.tvTime.setText(history.getDisplayTime());

        holder.itemView.setOnClickListener(v -> {
            if (listener != null) {
                listener.onItemClick(history);
            }
        });

        holder.itemView.setOnLongClickListener(v -> {
            if (onItemLongClickListener != null) {
                onItemLongClickListener.onItemLongClick(histories.get(position));
            }
            return true;
        });

    }

    @Override
    public int getItemCount() {
        return histories.size();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        TextView tvTitle;
        TextView tvTime;

        ViewHolder(View view) {
            super(view);
            tvTitle = view.findViewById(R.id.tvTitle);
            tvTime = view.findViewById(R.id.tvTime);
        }
    }
}
